#!/user/bin/env python3
# -*- coding: utf-8 -*-
from Common.getpath import get_root_path
from Common.loggers import Logger
import json
from Common.yaml_util import YamlUtil


class Assertions:
    def __init__(self, yaml_data):
        self.log = Logger().get_logger()
        self.validate = yaml_data

    def assert_code(self, code):
        """
        验证response状态码
        """
        expected_code = self.validate["validate"]["code"]
        print(code)
        print("---------------------------=+++++++++++++++++++++++++++++++++++++++++++++++++++")
        print(expected_code)
        try:
            assert code == expected_code
            return True
        except:
            self.log.info("statusCode error, expected_code is %s, statusCode is %s " % (expected_code, code))

            raise

    def assert_body(self, body):
        """
        验证response body中任意属性的值
        """
        expected_msg = self.validate["validate"]["code"]["body_msg"]
        try:
            assert body == expected_msg
            return True

        except:
            self.log.info(
                "Response body msg != expected_msg, expected_msg is %s, body_msg is %s" % (expected_msg, body))

            raise

    def assert_in_text(self, body):
        """
        验证response body中是否包含预期字符串
        """
        expected_msg = self.validate["validate"]["code"]['in_text']
        try:
            text = json.dumps(body, ensure_ascii=False)
            # print(text)
            assert expected_msg in text
            return True
        except:
            self.log.info("Response body Does not contain expected_msg, expected_msg is %s" % expected_msg)

            raise

    def assert_text(self, body):
        """
        验证response body中是否等于预期字符串
        :param body:
        :param expected_msg:
        :return:
        """
        expected_msg = self.validate["validate"]["code"]["assert_text"]
        try:
            assert body == expected_msg
            return True
        except:
            self.log.info("Response body != expected_msg, expected_msg is %s, body is %s" % (expected_msg, body))

            raise

    def assert_time(self, time):
        """
        验证response body响应时间小于预期最大响应时间,单位：毫秒
        """
        expected_time = self.validate["validate"]["code"]["assert_time"]
        try:
            assert time < expected_time

            return True

        except:
            self.log.info("Response time > expected_time, expected_time is %s, time is %s" % (expected_time, time))

            raise
